package io.github.mymonstercat.controller;

import io.github.mymonstercat.entity.VerificationVo;
import io.github.mymonstercat.entity.attachmentCheck.AttachmentResponse;
import io.github.mymonstercat.entity.attachmentCheck.AttachmentType;
import io.github.mymonstercat.service.AttachmentCheckService;
import io.github.mymonstercat.service.FileWarningService;
import io.github.mymonstercat.service.TicketVisitsService;
import io.github.mymonstercat.utils.FileUtils;
import io.github.mymonstercat.utils.Verification;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;

@Slf4j
@RestController
@RequestMapping("/v2")
public class AttachmentCheckController {

    private static final String STANDARD_PREFIX = "BZ";

    private static final String NON_STANDARD_PREFIX = "FB";

    @Value("${file.upload.window}")
    private String window;

    @Value("${file.upload.linux}")
    private String linux;

    @Resource
    private AttachmentCheckService attachmentCheckService;

    @Autowired
    private TicketVisitsService ticketVisitsService;

    // 附件校验接口
    @PostMapping("/attachmentCheck")
    public AttachmentResponse attachmentCheck(@RequestParam("file") MultipartFile file,
                                @RequestParam("attachmentCode") String attachmentCode,
                                @RequestParam("attachmentName") String attachmentName,
                                @RequestParam("fileId") String fileId) {

        // 通过附件编码判断PDF是标准的还是非标准的
        AttachmentType attachmentType = checkString(attachmentCode);
        if (attachmentType == AttachmentType.ERROR) {
            return AttachmentResponse.error("附件编码有误");
        }

        // 接口开始执行时间
        long startTime = System.nanoTime();

        // 判断文件类型
        VerificationVo verificationVo = Verification.validateFile(file);

        if (0 == verificationVo.getStatus()) {
            // 结束计时
            long endTime = System.nanoTime();
            // 计算并输出执行时间，单位为秒
            double executionTime = (endTime - startTime) / 1.0e9;
            ticketVisitsService.saveVisits("接口执行失败，原因为:" + verificationVo.getMessage() + "。执行时间为:" + executionTime + "秒", "log");
            return AttachmentResponse.error(verificationVo.getMessage());
        }

        String pdfPath = null;
        try {
            pdfPath = FileUtils.upload(file, window, linux);
            // 获取图片的保存路径
            String imageOutputPath = FileUtils.getPath(window, linux);
            // 调用 service 层处理 PDF 并做 OCR 识别
            return attachmentCheckService.attachmentCheck(attachmentCode, pdfPath, imageOutputPath, attachmentType, fileId, verificationVo.getStatus());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 删除文件
            if (pdfPath != null) {
                File fileToDelete = new File(pdfPath);
                if (fileToDelete.exists()) {
                    boolean deleted = fileToDelete.delete();
                    if (!deleted) {
                        log.info("删除文件失败: " + pdfPath);
                    } else {
                        log.info("删除文件成功: " + pdfPath);
                    }
                }
            }
        }
        return AttachmentResponse.error("系统异常");
    }

    private AttachmentType checkString(String input) {
        if (input.startsWith(STANDARD_PREFIX)) {
            return AttachmentType.STANDARD;
        } else if (input.startsWith(NON_STANDARD_PREFIX)) {
            return AttachmentType.NON_STANDARD;
        } else {
            return AttachmentType.ERROR;
        }
    }
}
